"""
向量数据库回退方案
在ChromaDB安装完成前提供临时解决方案
"""

import os
import json
from typing import List, Dict, Any, Optional, Tuple
from .vector_db import VectorDB, KnowledgeVectorDB


class ChromaDBStub:
    """ChromaDB桩实现，提供相同接口但使用现有向量数据库"""
    
    def __init__(self, collection_name: str = "knowledge_base", persist_directory: str = "./chroma_db"):
        """初始化桩实现"""
        self.collection_name = collection_name
        self.vector_db = VectorDB()
        print(f"⚠️  使用向量数据库回退模式 (等待ChromaDB安装完成)")
    
    def add_documents(self, documents: List[str], metadatas: Optional[List[Dict]] = None):
        """添加文档"""
        self.vector_db.add_documents(documents, metadatas)
    
    def search(self, query: str, n_results: int = 5) -> List[Tuple[str, float, Dict]]:
        """搜索文档"""
        results = self.vector_db.search(query, n_results)
        
        # 转换为ChromaDB格式
        formatted_results = []
        for doc, score, metadata in results:
            formatted_results.append((doc, score, metadata or {}))
        
        return formatted_results
    
    def get_document_count(self) -> int:
        """获取文档数量"""
        return len(self.vector_db.documents)
    
    def clear(self):
        """清空集合"""
        self.vector_db.clear()
    
    def save(self, file_path: str):
        """保存"""
        self.vector_db.save(file_path)
    
    def load(self, file_path: str):
        """加载"""
        self.vector_db.load(file_path)


class KnowledgeChromaDBStub:
    """知识库ChromaDB桩实现"""
    
    def __init__(self, role_name: str):
        """初始化"""
        self.role_name = role_name
        self.vector_db = KnowledgeVectorDB(role_name)
        print(f"⚠️  {role_name}: 使用知识库向量数据库回退模式")
    
    def add_qa_pair(self, question: str, answer: str, metadata: Optional[Dict] = None):
        """添加问答对"""
        self.vector_db.add_qa_pair(question, answer, metadata)
    
    def search_question(self, query: str, n_results: int = 3) -> List[Tuple[str, str, float]]:
        """搜索问题"""
        return self.vector_db.search_question(query, n_results)
    
    def batch_add_qa_pairs(self, qa_pairs: List[Dict]):
        """批量添加问答对"""
        for qa in qa_pairs:
            question = qa.get('question', '')
            answer = qa.get('answer', '')
            if question and answer:
                self.add_qa_pair(question, answer, qa)
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        return {
            "role": self.role_name,
            "document_count": self.vector_db.get_document_count(),
            "mode": "fallback"
        }


def get_chroma_implementation():
    """获取ChromaDB实现（真实或回退）"""
    try:
        # 尝试导入真实ChromaDB
        from .chroma_db import KnowledgeChromaDB
        print("✅ 使用真实的ChromaDB实现")
        return KnowledgeChromaDB
    except ImportError:
        print("⚠️  ChromaDB未安装，使用回退实现")
        return KnowledgeChromaDBStub
    except Exception as e:
        print(f"⚠️  ChromaDB导入错误: {e}，使用回退实现")
        return KnowledgeChromaDBStub


# 导出兼容接口
KnowledgeChromaDB = get_chroma_implementation()


def test_fallback():
    """测试回退功能"""
    print("=== 测试向量数据库回退功能 ===")
    
    # 测试回退实现
    kb = KnowledgeChromaDB("test_fallback")
    
    # 添加测试数据
    test_data = [
        {"question": "测试问题1", "answer": "测试答案1"},
        {"question": "测试问题2", "answer": "测试答案2"}
    ]
    
    kb.batch_add_qa_pairs(test_data)
    
    # 测试搜索
    results = kb.search_question("测试")
    print(f"搜索结果: {len(results)} 条")
    
    for question, answer, score in results:
        print(f"  - {question} -> {answer} (分数: {score:.3f})")
    
    print("✅ 回退功能测试完成")


if __name__ == "__main__":
    test_fallback()